<template>
  <view class="page">
    <view class="detail-card" :class="{ loading: isLoading }">
      <!-- 顶部标题 + 状态标签 -->
      <view class="detail-header">
        <text class="title">{{ detail.applicationNumber }}</text>
        <view class="status-badge" :style="statusBadgeStyle">
          {{ statusText }}
        </view>
      </view>

      <!-- 申请信息 -->
      <view class="info-group">
        <view class="group-title">申请信息</view>
        <view class="line">
          <text class="label">出发地：</text>
          <text class="value">{{ detail.departureLocation }}</text>
        </view>
        <view class="line">
          <text class="label">目的地：</text>
          <text class="value">{{ detail.destination }}</text>
        </view>
        <view class="line">
          <text class="label">预计时间：</text>
          <text class="value">
            <text>{{ fmtTime(detail.startTime) }} -</text>
            <text class="ml-auto"> {{ fmtTime(detail.endTime) }} </text>
          </text>
        </view>
        <view class="line">
          <text class="label">实际时间：</text>
          <text class="value">
            <text>{{ fmtTime(orders.actualStartTime) }} -</text>
            <text class="ml-auto"> {{ fmtTime(orders.actualEndTime) }} </text>
          </text>
        </view>
        <view class="line">
          <text class="label">乘车人数：</text>
          <text class="value">{{ detail.passengers }}人</text>
        </view>
        <view class="line">
          <text class="label">司机需求：</text>
          <text class="value">{{
            detail.needDriver ? "需要司机" : "不需要司机"
          }}</text>
        </view>
        <view class="line">
          <text class="label">事由：</text>
          <text class="value">{{ detail.purpose || "无" }}</text>
        </view>
      </view>

      <!-- 状态信息 -->
      <view class="info-group">
        <view class="group-title">状态信息</view>
        <view class="line">
          <text class="label">申请状态：</text>
          <text class="value">{{ statusText }}</text>
        </view>
        <view class="line">
          <text class="label">申请时间：</text>
          <text class="value">{{ detail.createdAt }}</text>
        </view>
      </view>

      <!-- 司机信息模块 -->
      <view v-if="driver.userId" class="driver-section">
        <view class="driver-header">司机信息</view>
        <view class="driver-content">
          <image class="driver-avatar" :src="driver.avatar" mode="aspectFill" />
          <view class="driver-info">
            <text class="driver-name">{{
              driver.name || driver.driverId
            }}</text>

            <view class="driver-meta">
              <view class="meta-item"
                >驾龄: {{ driver.drivingExperience }}年</view
              >
              <view class="meta-item">驾照类型: {{ driver.licenseType }}</view>
            </view>

            <view class="driver-rating">
              <text class="rating-label">评分：</text>
              <uni-rate
                :value="driver.rating || 5"
                :readonly="true"
                :size="14"
              />
              <text class="rating-score">{{ driver.rating || 5 }} 分</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button
          v-if="detail.status === 'pending'"
          class="action-btn btn-cancel"
          @tap="onCancel"
          :disabled="isLoading"
        >
          {{ isLoading ? "处理中..." : "取消申请" }}
        </button>
        <button
          v-if="detail.status === 'dispatched' && !detail.needDriver"
          class="action-btn btn-start"
          @tap="onStart"
          :disabled="isLoading"
        >
          {{ isLoading ? "处理中..." : "开始任务" }}
        </button>
        <button
          v-if="detail.status === 'in_progress' && !detail.needDriver"
          class="action-btn btn-complete"
          @tap="onComplete"
          :disabled="isLoading"
        >
          {{ isLoading ? "处理中..." : "完成任务" }}
        </button>
        <button
          v-if="detail.status === 'completed' && detail.needDriver"
          class="action-btn btn-comment"
          @tap="onComment"
          :disabled="isLoading"
        >
          评价行程
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { formatTaskTime } from "@/utils/formatTaskTime.js";
export default {
  name: "applicationDetail",
  data() {
    return {
      detail: {},
      driver: {},
      orders: {},
      isLoading: false,
    };
  },
  computed: {
    statusText() {
      const map = {
        pending: "审批中",
        approved: "已批准",
        rejected: "已拒绝",
        dispatched: "已派车",
        in_progress: "进行中",
        completed: "已完成",
        cancelled: "已取消",
      };
      return map[this.detail.status] || this.detail.status;
    },
    statusBadgeStyle() {
      const colorMap = {
        pending: { backgroundColor: "#faad14", color: "#fff" },
        approved: { backgroundColor: "#52c41a", color: "#fff" },
        rejected: { backgroundColor: "#ff4d4f", color: "#fff" },
        completed: { backgroundColor: "#1890ff", color: "#fff" },
        in_progress: { backgroundColor: "#52c41a", color: "#fff" },
        dispatched: { backgroundColor: "#52c41a", color: "#fff" },
        cancelled: { backgroundColor: "#ff4d4f", color: "#fff" },
      };

      return (
        colorMap[this.detail.status] || {
          backgroundColor: "#d9d9d9",
          color: "#fff",
        }
      );
    },
  },
  onLoad(opt) {
    if (opt.data) {
      const id = JSON.parse(decodeURIComponent(opt.data)).id;
      // 请求
      this.get_detail_info(id);
    }
  },
  methods: {
    fmtTime: formatTaskTime,
    async get_detail_info(id) {
      try {
        this.isLoading = true;
        const res = await uni.$http.get(
          `/sys/applications/userAppDetail/${id}`
        );
        this.detail = res.data.data.application;
        this.driver = res.data.data.driver;
        this.orders = res.data.data.order;
      } catch (e) {
        uni.showToast({ title: "加载失败", icon: "none" });
      } finally {
        this.isLoading = false;
      }
    },
    onCancel() {
      uni.showModal({
        title: "提示",
        content: "确定要取消该申请吗？",
        success: async (res) => {
          if (res.confirm) {
            try {
              this.isLoading = true;
              const res = await uni.$http.put(
                `/sys/applications/${this.detail.id}/cancel`
              );
              uni.showToast({ title: res.data.message, icon: "success" });

              // 更新本地状态
              this.detail.status = "cancelled";

              // 延迟返回，确保用户看到成功提示
              setTimeout(() => {
                this.refreshAndBack();
              }, 1500);
            } catch (e) {
              uni.showToast({ title: e.data?.msg || "操作失败", icon: "none" });
            } finally {
              this.isLoading = false;
            }
          }
        },
      });
    },
    onStart() {
      uni.showModal({
        title: "提示",
        content: "确定开始任务？",
        success: async (res) => {
          if (!res.confirm) return;
          try {
            this.isLoading = true;
            await uni.$http.put(`/sys/applications/start/${this.detail.id}`);
            uni.showToast({ title: "任务已开始", icon: "success" });

            // 更新本地状态
            this.detail.status = "in_progress";

            // 延迟返回，确保用户看到成功提示
            setTimeout(() => {
              this.refreshAndBack();
            }, 1500);
          } catch (e) {
            uni.showToast({ title: e.data?.msg || "开始失败", icon: "none" });
            this.isLoading = false;
          }
        },
      });
    },
    onComplete() {
      uni.showModal({
        title: "提示",
        content: "确定完成任务？",
        success: async (res) => {
          if (!res.confirm) return;
          try {
            this.isLoading = true;
            uni.navigateTo({
              url: `/pages/taskComplete/taskComplete?id=${this.detail.applicationNumber}`,
            });
          } catch (e) {
            uni.showToast({ title: e.data?.msg || "完成失败", icon: "none" });
          } finally {
            this.isLoading = false;
          }
        },
      });
    },
    onComment() {
      uni.navigateTo({
        url: `/pages/orderComment/orderComment?id=${this.detail.id}`,
      });
    },
    refreshAndBack() {
      // 先返回页面，再尝试刷新上级页面数据
      uni.navigateBack();

      // 使用事件总线或全局状态管理通知上级页面刷新
      // 这里使用setTimeout确保返回动画完成后再刷新
      setTimeout(() => {
        const pages = getCurrentPages();
        const prev = pages[pages.length - 2];
        if (prev && prev.$vm && prev.$vm.getApplicationList) {
          prev.$vm.getApplicationList();
        }
      }, 500);
    },
  },
};
</script>

<style lang="scss" scoped>
/* 样式与原来保持一致，直接复制即可 */
.page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 20rpx;
  box-sizing: border-box;
}

.detail-card {
  background: linear-gradient(135deg, #ffffff 0%, #f9fafb 100%);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 30rpx;
  position: relative;
  overflow: hidden;
}

.detail-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 10rpx;
  background: linear-gradient(90deg, #1890ff 0%, #52c41a 100%);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1f2d3d;
}

.info-group {
  margin-bottom: 30rpx;
}

.group-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  padding-left: 15rpx;
  border-left: 8rpx solid #1890ff;
}

.line {
  display: flex;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  padding: 15rpx 0;
  border-bottom: 1rpx dashed #eee;
}

.line:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  flex: 0 0 180rpx;
  font-weight: 500;
}

.value {
  color: #333;
  flex: 1;
  font-weight: 400;
  line-height: 1.6;
}

/* 司机信息样式 */
.driver-section {
  margin-top: 40rpx;
  padding: 30rpx;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  border-radius: 16rpx;
  border: 1rpx solid #91d5ff;
  position: relative;
  overflow: hidden;
}

.driver-section::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 120rpx;
  height: 120rpx;
  background: rgba(24, 144, 255, 0.1);
  border-radius: 0 0 0 100%;
}

.driver-header {
  font-size: 32rpx;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 25rpx;
  display: flex;
  align-items: center;
}

.driver-header::before {
  content: "👨‍💼";
  margin-right: 10rpx;
  font-size: 36rpx;
}

.driver-content {
  display: flex;
  align-items: center;
}

.driver-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 25rpx;
  background-color: #f0f0f0;
  border: 3rpx solid #fff;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
}

.driver-info {
  flex: 1;
}

.driver-name {
  font-size: 32rpx;
  color: #1f2d3d;
  display: block;
  margin-bottom: 15rpx;
  font-weight: 600;
}

.driver-meta {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15rpx;
}

.meta-item {
  margin-right: 25rpx;
  margin-bottom: 12rpx;
  font-size: 24rpx;
  color: #666;
  display: flex;
  align-items: center;
}

.meta-item::before {
  content: "•";
  margin-right: 8rpx;
  color: #1890ff;
}

.driver-rating {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #666;
}

.rating-label {
  margin-right: 10rpx;
  color: #333;
}

.rating-score {
  margin-left: 10rpx;
  color: #faad14;
  font-weight: 600;
}

/* 按钮样式 */
.action-buttons {
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
}

.action-btn {
  margin: 0 0 20rpx 0;
  height: 90rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
}

.action-btn:active {
  transform: translateY(4rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.btn-cancel {
  background-color: #ff4d4f;
  color: #fff;
}

.btn-start {
  background-color: #1890ff;
  color: #fff;
}

.btn-complete {
  background-color: #52c41a;
  color: #fff;
}

.btn-comment {
  background-color: #faad14;
  color: #fff;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  font-weight: 500;
}

/* 加载状态 */
.loading {
  opacity: 0.7;
  pointer-events: none;
}

.action-btn[disabled] {
  opacity: 0.6;
  pointer-events: none;
}

.time-row {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #666;
  .ml-auto {
    margin-left: auto;
  }
}
</style>
